package app.vendorportal;

import core.framework.log.LogSettings;
import core.framework.web.DefaultServiceConfig;
import core.framework.web.runtime.RuntimeEnvironment;
import core.framework.web.runtime.RuntimeSettings;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;

@Configuration
@ComponentScan(basePackageClasses = WebConfig.class)
@EnableTransactionManagement(proxyTargetClass = true)
public class WebConfig extends DefaultServiceConfig {
    @Inject
    Environment env;
    @Inject
    EntityManagerFactory entityManagerFactory;

    @Override
    public RuntimeSettings runtimeSettings() {
        RuntimeSettings settings = new RuntimeSettings();
        settings.setEnvironment(env.getProperty("site.environment", RuntimeEnvironment.class, RuntimeEnvironment.PROD));
        settings.setVersion(version());
        return settings;
    }

    @Override
    public LogSettings logSettings() {
        LogSettings settings = LogSettings.get();
        //settings.filterLog(new DropShipServiceLogMessageFilter());
        return settings;
    }

    private String version() {
        String version = env.getProperty("runtime.version");
        if (version.contains("${"))
            return "current"; // for local build, where version is not populated
        return version;
    }

//    @Bean
//    @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
//    APIRequestContext apiRequestContext() {
//        return new APIRequestContext();
//    }

//    @Bean
//    public ClientAuthInterceptor clientAuthInterceptor() {
//        return new ClientAuthInterceptor();
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestContextInterceptor());
        registry.addInterceptor(trackInterceptor());
        OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor = new OpenEntityManagerInViewInterceptor();
        openEntityManagerInViewInterceptor.setEntityManagerFactory(entityManagerFactory);
        registry.addWebRequestInterceptor(openEntityManagerInViewInterceptor);
        //registry.addInterceptor(clientAuthInterceptor());
    }
}
